import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

void main() => runApp(RootApp());

// 定义根目录Wigdget
class RootApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // 根视图
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  double current = 0.0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Dio网络请求 GET")),
      body: Row(
        children: [
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                FlatButton(
                  onPressed: () {
                    // TODO
                    downloadFile();
                  },
                  child: Text("下载文件"),
                ),
                SizedBox(height: 50),
                SizedBox(
                  width: 60,
                  height: 60,
                  child: CircularProgressIndicator(value: current),
                )
              ],
            ),
          ),
        ],
      ),
    );
  }

  void downloadFile() async {
    // 申请写文件权限
    // await checkPermissFunction();
    Dio dio = new Dio();
    // 请求地址
    String apkUrl = "http://pic.studyyoun.com/2.1.2.apk";
    String savePath = await getPhoneLocalPath();
    String apkName = "rk.apk";

    // 发起download请求

    Response response = await dio.download(apkUrl, "$savePath$apkName",
        onReceiveProgress: (int received, int total) {
      if (total != -1) {
        print((received / total * 100).toStringAsFixed(0) + "%");
        setState(() {
          current = received / total;
        });
      }
    });
  }

  // checkPermissFunction() async {
  //   if (Theme.of(context).platform == TargetPlatform.android) {
  //     PermissionStatus permission = await PermissionHandler()
  //         .checkPermissionStatus(PermissionGroup.storage);
  //     if (permission != PermissionStatus.granted) {
  //       Map<PermissionGroup, PermissionStatus> permissions =
  //           await PermissionHandler()
  //               .requestPermissions([PermissionGroup.storage]);
  //       if (permissions[PermissionGroup.storage] != PermissionStatus.granted) {
  //         return false;
  //       }
  //     }
  //   } else {
  //     return true;
  //   }
  //   return false;
  // }

// 获取手机文件保存路径
  Future<String> getPhoneLocalPath() async {
    final directory = Theme.of(context).platform == TargetPlatform.android
        ? await getExternalStorageDirectory()
        : await getApplicationDocumentsDirectory();
    return directory.path;
  }
}
